import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Main 
{

	public static void main(String[] args) throws IOException
	{
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(7777);
			Socket fromclient;
			while(true)
			{
				System.out.println("Ожидание");
				fromclient = ss.accept();
				System.out.println("Входящее соединение...");
				InputStream in = fromclient.getInputStream();
		        DataInputStream din = new DataInputStream(in);
		        long fileSize = din.readLong();
		        System.out.println("Размер входящего файла: "+fileSize);
		        String fileName = din.readUTF();
		        System.out.println("Имя входящего файла: "+fileName);
		        byte[] buffer = new byte[64*1024];
		        FileOutputStream outF = new FileOutputStream(fileName);
		        int count, total = 0;
		        
		        while ((count = din.read(buffer)) != -1)
		        {               
		            total += count;
		            outF.write(buffer, 0, count);
		            outF.flush();
		            if(total == fileSize)
		            {
		                break;
		            }
		        }
		        outF.close();
		        System.out.println("Файл получен");
			}
		} 
		catch (IOException e) 
		{
			System.err.println("IO Error");
			try
			{
				ss.close();
			}
			catch (NullPointerException e1)
			{
				System.err.println("Ошибка закрытия сокета");
			}
		}
	}

}
